import 'dart:convert';

import 'package:bruno/bruno.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:miuu_note_app/dao/snippet_dao.dart';
import 'package:miuu_note_app/page/snippet_add_update.dart';
import 'package:miuu_note_app/page/snippet_detail.dart';

import '../model/snippet_entity.dart';

class SnippetPage extends StatefulWidget {
  const SnippetPage({super.key});

  @override
  State<SnippetPage> createState() => _SnippetPageState();
}

class _SnippetPageState extends State<SnippetPage> {
  SnippetPageEntity? _snippetPageEntity;
  TextEditingController? textEditingController;

  @override
  void initState() {
    super.initState();
    _getSnippetPage({});
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
            floatingActionButton: FloatingActionButton(
              heroTag: 'addSnippet',
              onPressed: () {
                Navigator.push(
                        context,
                        MaterialPageRoute(
                            builder: (context) => const SnippetAdd()))
                    .then((value) {
                  if (value != null) {
                    _getSnippetPage({});
                  }
                });
              },
              child: const Icon(Icons.add),
            ),
            appBar: BrnSearchAppbar(
              autoFocus: false,
              showDivider: false,
              themeData: BrnAppBarConfig.light(),
              hint: '请输入笔记名称',
              controller: textEditingController,
              searchBarInputChangeCallback: (input) {},
              searchBarInputSubmitCallback: (input) {
                _getSnippetPage({
                  "title": input,
                });
              },
              dismissClickCallback: (controller, update) {
                controller.text = "";
                _getSnippetPage({});
              },
            ),
            body: SingleChildScrollView(
              physics: const AlwaysScrollableScrollPhysics(),
              child: Container(
                  margin:
                      const EdgeInsets.symmetric(horizontal: 0, vertical: 10),
                  alignment: Alignment.centerLeft,
                  child: _buildWidget(context)),
            )));
  }

  Widget _buildWidget(BuildContext context) {
    List<Widget> mGoodsCard = [];
    Widget content;
    _snippetPageEntity?.todoMaps.forEach((key, value) {
      mGoodsCard.add(Column(
        children: [
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 0),
            child: Align(
              alignment: Alignment.centerLeft,
              child: Text(key),
            ),
          ),
          ListView.separated(
            separatorBuilder: (_, __) => const SizedBox(
              height: 10,
            ),
            itemCount: value.length,
            padding: const EdgeInsets.all(10),
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemBuilder: (BuildContext ctxt, int index) {
              SnippetModel item = value[index];
              return ListTile(
                  tileColor: Colors
                      .white, // If current item is selected show blue color
                  title: Row(
                    children: [
                      const Icon(
                        // 图标
                        Icons.book,
                        // 图标的颜色
                        color: Color.fromARGB(255, 104, 187, 254),
                        // 图标的大小
                        size: 25,
                      ),
                      Container(
                        padding: const EdgeInsets.only(left: 5),
                        child: GestureDetector(
                          child: Text(
                            item.title ?? "",
                            style: const TextStyle(
                              fontSize: 17,
                            ),
                          ),
                          onTapUp: (value) {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) => const SnippetDetail(),
                                  settings: RouteSettings(arguments: {
                                    'snippetId': item.snippetId
                                  }) // 需要跳转的页面
                                  ),
                            ).then((value) {
                              if (value != null) {
                                // _getTodoList({'itemStatus': false});
                              }
                            });
                          },
                        ),
                      ),
                    ],
                  ),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        alignment: Alignment.centerLeft,
                        margin: const EdgeInsets.only(
                            top: 2, left: 0, bottom: 10), //设置四周外边距为20
                        child: Text(
                          maxLines: 2,
                          overflow: TextOverflow.ellipsis,
                          value[index].content ?? "",
                          style: const TextStyle(
                            fontSize: 14,
                            color: Color.fromARGB(255, 151, 151, 151),
                          ),
                        ),
                      ),
                      Text(
                        value[index].updateTime ?? "",
                        style: const TextStyle(
                            fontSize: 13,
                            color: Color.fromARGB(255, 151, 151, 151)),
                      ),
                    ],
                  ));
            },
          )
        ],
      ));
    });

    content = Column(
      children: mGoodsCard,
    );

    return content;
  }

  void _getSnippetPage(Map<String, dynamic> map) async {
    SnippetPageEntity? entity = await SnippetPageDao.fetch(map);
    setState(() {
      _snippetPageEntity = entity;
    });
  }
}
